package mo_gorm

import (
	"go.uber.org/zap"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"strconv"
)

func DoFillModelSnowflakeIdBeforeCreate(db *gorm.DB) {
	if db.Statement.Schema == nil {
		return
	}
	for _, field := range db.Statement.Schema.PrimaryFields {
		isAutoIncrement := isFieldAutoIncrement(field)
		if !isAutoIncrement {
			value, isZero := field.ValueOf(db.Statement.Context, db.Statement.ReflectValue)
			MoLogger.Debug("DoFillModelSnowflakeIdBeforeCreate", zap.Any("value", value))
			if isZero {
				switch field.DataType {
				case schema.Int, schema.Uint:
					if err := field.Set(db.Statement.Context, db.Statement.ReflectValue, SnowflakeNode.Generate().Int64()); err != nil {
						MoLogger.Warn("DoFillModelSnowflakeIdBeforeCreate:set")
					}
				case schema.String:
					if err := field.Set(db.Statement.Context, db.Statement.ReflectValue, strconv.FormatInt(SnowflakeNode.Generate().Int64(), 10)); err != nil {
						MoLogger.Warn("DoFillModelSnowflakeIdBeforeCreate:set")
					}
				}
			}
			break
		}
	}
}

func isFieldAutoIncrement(field *schema.Field) bool {
	//发现mysql中，没设置成AutoIncrement,但是值也是true
	if !field.AutoIncrement {
		return false
	}
	autoIncrementStr := GetGormTagValByName(field.Tag.Get("gorm"), "autoIncrement")
	if autoIncrementStr == "" || "true" == autoIncrementStr {
		return true
	}
	return false
}
